<template>
  <div class="page-controller">
    <el-container>
      <el-aside width="240px" class="tree_css">
        <h3>组织机构列表</h3>
        <FITree1
          v-if="isShowTree"
          class="tree_box"
          :treeListObj="treeListObj"
          :filter-node-method="filterNode"
          :showFilter="true"
          :showCheckbox="false"
          @nodeClick="nodeClick"
        ></FITree1>
      </el-aside>
      <el-container>
        <el-main>
          <FISearchForm
            class="box-radius2"
            ref="ruleFormRef"
            :id="`inqu_${tableId}`"
            v-model:form-value="state.query"
            :exclude-values="['orgId']"
            :table-column="columns"
            :showCollapse="false"
            :wrapperSpan="searchWrapperSpan"
            @submit="searchFn"
          >
            <el-col :span="searchWrapperSpan" class="flex-center">
              <FIFormItem prop="groupEname" label="管理员账号">
                <FIInput v-model="state.query.orgAdmLoginName" clearable />
              </FIFormItem>
            </el-col>
            <el-col :span="searchWrapperSpan" class="flex-center">
              <FIFormItem name="groupCname" label="管理员名称">
                <FIInput v-model="state.query.groupCname" clearable />
              </FIFormItem>
            </el-col>
          </FISearchForm>
          <div class="margin-bottom20"></div>
          <FITable
            ref="tableRef"
            class="box-radius2"
            title="岗位列表"
            :id="`result_${tableId}`"
            :readonly="false"
            :data="state.dataList"
            primaryKey="groupId"
            v-model:columns="columns"
            :isLoading="isTableLoading"
            insertable
            deletable
            :showRowNo="true"
            :saveSuccessful="saveSuccessful"
            @row-add="rowAdd"
            :pageConfig="pageConfig"
            @row-add-save="addRowSave"
            @table-refresh="searchFn"
            @selection-change="handleSelectionChange"
            @size-change="handleSizeChange"
            @current-page-change="handleCurrentChange"
            @action-click="actionClick"
            @row-delete="deleteRow"
            @on-cell-select="selectClick"
          >
          </FITable>
        </el-main>
      </el-container>
    </el-container>
  </div>
</template>
<script lang="ts" setup>
import { reactive, onMounted, ref, computed, watch } from 'vue'
import FISearchForm from '@/components/FISearchForm.vue'
import FIFormItem from '@/components/FIFormItem.vue'
import FIInput from '@/components/FIInput.vue'
import FIButton from '@/components/FIButton.vue'
import FIPopconfirmBtn from '@/components/FIPopconfirmBtn.vue'
import FITable from '@/components/FITable/index.vue'
import FICascaderTree from '@/components/FICascaderTree.vue'
import FITree1 from '@/components/FITree1.vue'
import { apiRequestPost } from '@/api/globalApi.js'
import LocalCache from '@/utils/cache'
import { ElMessage } from 'element-plus'
import { useMessage } from '@/hooks/message'
import type { PageConfig, Column } from '@/types/components'
import { useRoute } from 'vue-router'
import { initSearchData } from '@/utils/common'
import { getQueryTableCache } from '@/utils/cacheUtils'
import { apiDelete01, apiSave01, apiQuery01, apiDeptMaintquery, apiPostquery, apiGetXslvDeptTree } from '@/api/user'
import { getCurrentInstance } from 'vue'
const { proxy } = getCurrentInstance() // 获取当前组件实例上下文
const route = useRoute()

const searchWrapperSpan = 8
const showSearch = ref(true)
const setShow = ref(false)
const isTableLoading = ref(false)
// 页面编码
const tableId = 'usersManage'
// 保存成功按钮状态，默认不展示底部保存，取消按钮
const saveSuccessful = ref(false)
const tableRef = ref(null)
const editData = ref({})
const orgList = ref([])
const postList = ref([])
const userlistCurrent = ref(1)
const loadMoreEnd = ref(false)
const treeListObj = ref(null)
const state = reactive({
  query: {
    orgAdmLoginName: '',
    orgAdmUserName: '',
    orgId: '',
    current: '1',
    size: 10,
  },
  dataList: [],
})
const pageConfig: PageConfig = reactive({
  total: 0,
  currentPage: 1,
})
const columns: Column[] = reactive([
  {
    label: '管理员账号',
    prop: 'orgAdmLoginName',
    align: 'center',
    editable: true,
    editType: 'autoSelect',
    editConfig: {
      otherBinds: {
        apiUrl: '/rm2/userMaint/query',
        props: { value: 'loginName', label: 'loginName' },
        displayKey: ['loginName', 'userName'],
        searchParam: 'userAName',
      },
    },
  },
  {
    label: '管理员名称',
    prop: 'orgAdmUserName',
    align: 'center',
    queryName: '',
    editable: true,
    sortable: false,
    filterable: false,

    modelValue: { inputValue: '' },
    editType: 'input',
  },
  {
    label: '分级管理员管理权限',
    prop: 'orgPermManager',
    align: 'center',
    editType: 'select', // 显示类型: input 文本类型，date: 日期，textArea, select:单选，multiSelect:多选,time:时间，Cascader：级联选择器，custome:自定义
    editable: true,
    filterable: false,
    modelValue: { inputValue: '' },
    sortable: false,
    sortValue: '',
    editConfig: {
      options: [
        { value: '1', label: '是' },
        { value: '0', label: '否' },
      ],
    },
  },
  {
    label: '分级资源范围管理权限',
    prop: 'orgPermResRange',
    queryName: '',
    align: 'center',
    editType: 'select', // 显示类型: input 文本类型，date: 日期，textArea, select:单选，multiSelect:多选,time:时间，Cascader：级联选择器，custome:自定义
    editable: true,
    filterable: false,
    modelValue: { inputValue: '' },
    sortable: false,
    sortValue: '',
    editConfig: {
      options: [
        { value: '1', label: '是' },
        { value: '0', label: '否' },
      ],
    },
  },
  {
    label: '本级用户组管理权限',
    prop: 'orgPermUserGroup',
    align: 'center',
    editable: true,
    editType: 'select', // 显示类型: input 文本类型，date: 日期，textArea, select:单选，multiSelect:多选,time:时间，Cascader：级联选择器，custome:自定义
    filterable: false,
    modelValue: { inputValue: '' },
    sortable: false,
    sortValue: '',
    editConfig: {
      options: [
        { value: '1', label: '是' },
        { value: '0', label: '否' },
      ],
    },
  },
  {
    label: '分级用户组管理权限',
    prop: 'orgPermSubUserGroup',
    queryName: '',
    align: 'center',
    editType: 'select', // 显示类型: input 文本类型，date: 日期，textArea, select:单选，multiSelect:多选,time:时间，Cascader：级联选择器，custome:自定义
    editable: true,
    filterable: false,
    modelValue: { inputValue: '' },
    sortable: false,
    sortValue: '',
    editConfig: {
      options: [
        { value: '1', label: '是' },
        { value: '0', label: '否' },
      ],
    },
  },
  {
    label: '本级授权管理权限',
    prop: 'orgPermAuth',
    align: 'center',
    editType: 'select', // 显示类型: input 文本类型，date: 日期，textArea, select:单选，multiSelect:多选,time:时间，Cascader：级联选择器，custome:自定义
    editable: true,
    filterable: false,
    modelValue: { inputValue: '' },
    sortable: false,
    sortValue: '',
    editConfig: {
      options: [
        { value: '1', label: '是' },
        { value: '0', label: '否' },
      ],
    },
  },
  {
    label: '分级授权管理权限',
    prop: 'orgPermSubAuth',
    align: 'center',
    editType: 'select', // 显示类型: input 文本类型，date: 日期，textArea, select:单选，multiSelect:多选,time:时间，Cascader：级联选择器，custome:自定义
    editable: true,
    filterable: false,
    modelValue: { inputValue: '' },
    sortable: false,
    sortValue: '',
    editConfig: {
      options: [
        { value: '1', label: '是' },
        { value: '0', label: '否' },
      ],
    },
  },
  // {
  //   label: '',
  //   prop: 'action',
  //   actionConfig: [{ id: 'openGroupUser', type: 'set' }],
  // },
])
const changeEvent = (e) => {
  console.log(e, 'ppppp')
  if (!e) {
    state.query.postId = ''
  }
}
const selectClick = (scope, item) => {
  if (scope.column.property == 'orgAdmLoginName') {
    tableRef.value.setCellValue(scope.$index, 'orgAdmUserName', item.userName)
    tableRef.value.setCellValue(scope.$index, 'orgAdmId', item.userId)
  }
}
const checkedRows = ref([])
const handleSelectionChange = (e) => {
  checkedRows.value = e
}
const handleSizeChange = (e) => {
  pageConfig.pageSize = e
  pageConfig.currentPage = 1
  searchFn()
}
const handleCurrentChange = (e) => {
  pageConfig.currentPage = e
  searchFn('page')
}
// const selectClick = (data) => {
//   console.log(data, 'data123')
//   state.query.postId = data.postId
// }
const filterNode = (value: string, data: Tree) => {
  if (!value) return true
  return data.label.includes(value)
}
const nodeClick = (val) => {
  console.log(val, 'val123')
  // treeObj.value = val
  state.query.orgId = val.value
  // state.query.deptEname = val.orgEname,
  searchFn('query', '')
}
// const selectClick = (scope, item) => {
//   console.log(scope, item, '查看')
//   if (scope.column.property == 'deptEname') {
//     tableRef.value.setCellValue(scope.$index, 'deptCname', item.orgCname)
//     tableRef.value.setCellValue(scope.$index, 'orgId', item.orgId)
//   }
//   if (scope.column.property == 'postEname') {
//     tableRef.value.setCellValue(scope.$index, 'postCname', item.postCname)
//     tableRef.value.setCellValue(scope.$index, 'postId', item.postId)
//   }
// }
// const handleSelect = (item, index) => {
//   console.log(item, 'item123--orgId')
//   tableRef.value.setCellValue(index, 'deptCname', item.orgCname)
//   tableRef.value.setCellValue(index, 'orgId', item.orgId)
// }
// const handlePostSelect = (item, index) => {
//   console.log(item, 'item123--postId')
//   tableRef.value.setCellValue(index, 'postCname', item.postCname)
//   tableRef.value.setCellValue(index, 'postId', item.postId)
// }
//操作
const actionClick = (item, rowData, btnInfo) => {
  editData.value = rowData
  if (item.type == 'set') {
    setShow.value = true
  }
}
// const selectData = (val,name) =>{
//   console.log(val,name)
//   // deptCname
//   // orgSelect.label = name
//   // orgSelect.value = val
// }
const selectNode = (val) => {
  state.query.orgId = val
}
const searchFn = (type?: string, columnsVal?: any) => {
  const obj = initSearchData(type, columnsVal, columns, state.query)
  isTableLoading.value = true
  state.query = obj.queryData
  columns.values = obj.columns
  if (type == 'page') {
    state.query.current = pageConfig.currentPage
  } else {
    pageConfig.currentPage = 1
    state.query.current = 1
  }
  isTableLoading.value = true
  if (pageConfig.pageSize) state.query.size = pageConfig.pageSize
  const par = {
    ...state.query,
  }
  // const apiUrl = proxy.$Button_api('query', route.name)
  apiQuery01(par)
    .then((res) => {
      isTableLoading.value = false
      if (res.data.success) {
        state.dataList = res.data.data.result
        pageConfig.pageSize = Number(res.data.data.size)
        pageConfig.total = Number(res.data.data.count)
      } else {
        // ElMessage.error(res.data.message)
      }
    })
    .catch((error: any) => {
      isTableLoading.value = false
      // 处理错误
    })
}
const handleSave = () => {
  // for (let i of checkedRows.value) {
  //   if (!i.groupCname) {
  //     useMessage().warning('请输入用户组名称')
  //     return
  //   }
  //   if (!i.groupEname) {
  //     useMessage().warning('请输入用户组编码')
  //     return
  //   }
  // }
  isTableLoading.value = true
  saveSuccessful.value = false
  // const apiUrl = proxy.$Button_api('save', route.name)
  for (let i of checkedRows.value) {
    i['orgId'] = state.query.orgId
  }
  apiSave01(checkedRows.value)
    .then((res) => {
      isTableLoading.value = false
      if (res.data.success) {
        // saveSuccessful.value = true
        ElMessage.success(res.data.message)
        // tableRef.value.clearSelection()
        searchFn()
      } else {
        ElMessage.error(res.data.message)
      }
    })
    .catch((error: any) => {
      isTableLoading.value = false
    })
}
const deleteRow = () => {
  if (!checkedRows.value.length) {
    useMessage().warning('请选择一条数据')
    return
  }
  let ids = []
  Array.isArray(checkedRows.value) &&
    checkedRows.value.forEach((item: any) => {
      if (item?.orgId) {
        let obj = {
          orgId: item.orgId,
          orgAdmId: item.orgAdmId,
        }
        ids.push(obj)
      }
    })
  isTableLoading.value = true
  // const apiUrl = proxy.$Button_api('delete', route.name)
  apiDelete01(ids)
    .then((res) => {
      isTableLoading.value = false
      if (res.data.success) {
        useMessage().success(res.data.message)
        searchFn()
      }
    })
    .catch((error: any) => {
      isTableLoading.value = false
    })
}
const ruleFormRef = ref(null)

const addRowSave = (data) => {
  handleSave()
}
const getOrgList = () => {
  let par = {
    current: 1,
    size: 999,
  }
  apiDeptMaintquery(par)
    .then((res) => {
      if (res.data.success) {
        // orgList.value = res.data.data.result
        for (let i of res.data.data.result) {
          const obj = {
            orgCname: i.orgCname,
            orgEname: i.orgEname,
            orgId: i.orgId,
          }
          orgList.value.push(obj)
        }
      }
    })
    .catch((error: any) => {
      isTableLoading.value = false
      // 处理错误
    })
}
const getPostList = (query) => {
  let par = {
    postAName: query || '',
    current: userlistCurrent.value,
    size: 10,
  }
  apiPostquery(par)
    .then((res) => {
      if (res.data.success) {
        for (let i of res.data.data.result) {
          const obj = {
            postCname: i.postCname,
            postEname: i.postEname,
            postId: i.postId,
          }
          postList.value.push(obj)
        }
        if (query) {
          postList.value = []
          postList.value = res.data.data.result
        }
        postList.value = postList.value.concat(res.data.data.result)
        if (userlistCurrent.value * 10 >= res.data.data.count) {
          loadMoreEnd.value = true
        }
      }
    })
    .catch((error: any) => {
      isTableLoading.value = false
      // 处理错误
    })
}
const getTreeList = async () => {
  const { data } = await apiGetXslvDeptTree({ scene: 2 })
  if (data.success) {
    // dataList.value = data.data.subNodes
    treeListObj.value = data.data
    isShowTree.value = true
    console.log(treeListObj.value, '调用了')
  }
}
const isShowTree = ref(false)
const rowAdd = () => {
  console.log(checkedRows.value, 'checkedRows.value')
  for (let i of checkedRows.value) {

    if (i._isNew == 1) {
      if (i.orgPermManager == null || i.orgPermManager == '')
        i.orgPermManager = '1'
      if (i.orgPermResRange == null || i.orgPermResRange == '')
        i.orgPermResRange = '1'
      if (i.orgPermUserGroup == null || i.orgPermUserGroup == '')
        i.orgPermUserGroup = '1'
      if (i.orgPermSubUserGroup == null || i.orgPermSubUserGroup == '')
        i.orgPermSubUserGroup = '0'
      if (i.orgPermAuth == null || i.orgPermAuth == '')
        i.orgPermAuth = '1'
      if (i.orgPermSubAuth == null || i.orgPermSubAuth == '')
        i.orgPermSubAuth = '0'
    }

  }
}

onMounted(() => {
  getTreeList()
  // searchFn()
  // getOrgList()
  // getPostList('')
  // 获取查询条件缓存
  const { cachedQuery, cachedColumns } = getQueryTableCache(route.path, tableId, state.query, columns.values)
  if (cachedQuery) state.query = cachedQuery
  if (columns) columns.values = cachedColumns
})
</script>
<style lang="less" scoped>
.tree_css {
  background: #fff;
  position: relative;
  height: calc(100vh - 200px);
  h3 {
    font-size: 18px;
    line-height: 55px;
    padding-left: 15px;
    border-bottom: 1px solid #eee;
    margin-bottom: 20px;
    color: #000000;
    .icon_css {
      float: right;
      margin-top: 16px;
      margin-right: 12px;
    }
  }
}
</style>
